package com.feihong.txgw.ui.activity.user;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.EncryptUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.feihong.txgw.R;
import com.feihong.txgw.app.App;
import com.feihong.txgw.dialog.LiuLiangChaXunVerifyCardDialog;
import com.feihong.txgw.inter.contract.llcx.ITelSpaceContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.llcx.PhoneCardLocation;
import com.feihong.txgw.model.bean.llcx.UserPhoneCardPackageInfoEntity;
import com.feihong.txgw.model.bean.user.User;
import com.feihong.txgw.observer.SmsObserver;
import com.feihong.txgw.tx_precenter.TelSpaceMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.view.StatusView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * description ：用户服务  流量查询
 *
 * @author : wangziheng
 * creation date: 2017/7/4  12:210:42
 * @version 1.0
 */

@RuntimePermissions
public class LiuLiangChaXunActivity extends BaseMVPCompateActivity<ITelSpaceContract.AbTelSpaceMainprecenter> implements View.OnClickListener, ITelSpaceContract.ITelSpaceMainView {

    @BindView(R.id.query_Traffic_userIcon)
    ImageView mUserIcon;
    @BindView(R.id.query_traffic_userph)
    TextView mUserPhoneNum;
    /**
     * 基础套餐名
     */
    @BindView(R.id.query_traffic_package1)
    TextView mUserPackage1;
    /**
     * 详细套餐名
     */
    @BindView(R.id.query_traffic_package2)
    TextView mUserPackage2;
    /**
     * 月消费
     */
    @BindView(R.id.query_traffic_month_consume_money)
    TextView mMonthConsumeMoney;
    /**
     * 剩余话费
     */
    @BindView(R.id.query_traffic_remain_money)
    TextView mRemainCallMoney;
    /**
     * 剩余语音
     */
    @BindView(R.id.query_traffic_remain_call_min)
    TextView mRemainCallMin;
    /**
     * 当期积分
     */
    @BindView(R.id.query_traffic_integral)
    TextView mIntegral;
    /**
     * 免费通话分钟数
     */
    @BindView(R.id.query_traffic_call_min_tv)
    TextView mFreeCallAllMin;
    /**
     * 剩余通话分钟数
     */
    @BindView(R.id.query_traffic_remain_call_min_tv)
    TextView mFreeCallRemainMin;
    /**
     * 通话使用情况占比
     */
    @BindView(R.id.query_traffic_call_percenter)
    ProgressBar mUserFulCllPercent;

    /**
     * TODO 短信使用情况
     * 短信总数
     */
    @BindView(R.id.query_traffic_sms_count)
    TextView mSMSCounts;
    /**
     * 短信使用量
     */
    @BindView(R.id.query_traffic_remain_sms_count)
    TextView mRemainSMSCounts;
    /**
     * 短信使用量占比
     */
    @BindView(R.id.query_traffic_sms_count_percenter)
    ProgressBar mSMSPercent;
    /**
     * TODO 流量使用情况
     * 流量总数
     */
    @BindView(R.id.query_traffic_traffic)
    TextView mTrafficAll;
    /**
     * 流量使用量
     */
    @BindView(R.id.query_traffic_remain_traffic)
    TextView mRemainTraffic;
    /**
     * 流量使用量占比
     */
    @BindView(R.id.query_traffic__traffic_percente)
    ProgressBar mTrafficPercent;


    @BindView(R.id.lay_loading)
    RelativeLayout mLoadLayout;
    private LiuLiangChaXunVerifyCardDialog mVerifyCarDialog;

    @BindView(R.id.user_phone_head_layout)
    LinearLayout mHeadLayout;
    @BindView(R.id.user_phone_head_error_layout)
    LinearLayout mHeadErrorLayout;

    @BindView(R.id.llcx_btn_back)
    ImageView mBackBtn;

    @BindView(R.id.activity_llcx_status_layout)
    StatusView mStatusView;
    private String mCacheData;
    private boolean isCacheData = false;

    @Override
    public void setTheme() {
        isDrakFont = false;
    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_liuliang_chaxun;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mBackBtn.setOnClickListener(this);
        mLoadLayout.setVisibility(View.VISIBLE);
        setSpecificTitleLayout(mStatusView);
        mLoadLayout.setVisibility(View.VISIBLE);
        // 优先从缓存中获取
        mCacheData = App.getApp().getaCache().getAsString(EncryptUtils.encryptMD5ToString(LiuLiangChaXunActivity.class.getName()));
        if (!TextUtils.isEmpty(mCacheData)) {
            isCacheData = true;
            setCacheData(JSON.parseObject(mCacheData, UserPhoneCardPackageInfoEntity.class));
        }
        String strPic = null;
        User user = UserLoginInfo.getUserInfo();
        if (user != null) {
            strPic = user.getUserPic();
        }
        Drawable drawable = getResources().getDrawable(R.mipmap.user_head);
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(drawable)
                .error(drawable);
        Glide.with(this).load(TextUtils.isEmpty(strPic) ? null : strPic).apply(requestOptions).into(mUserIcon);
        mHeadErrorLayout.setOnClickListener(this);
    }

    @Override
    public void bindData() {

        mUserPhoneNum.setText(UserLoginInfo.getUserPhone());
        VertifyPhoneNum();

    }

    /**
     * 设置数据显示
      */
    private void setCacheData(UserPhoneCardPackageInfoEntity userPackage) {
        if (userPackage == null) {
            return;
        }
        mHeadLayout.setVisibility(View.VISIBLE);
        mHeadErrorLayout.setVisibility(View.GONE);
        mUserPackage1.setText(TextUtils.isEmpty(userPackage.getProductname()) ? getResources().getString(R.string.queryTraffic_other) : userPackage.getProductname());
        mUserPackage2.setText(TextUtils.isEmpty(userPackage.getCurPlanName()) ? getResources().getString(R.string.queryTraffic_no_other_package) : userPackage.getCurPlanName());
        mMonthConsumeMoney.setText(TextUtils.isEmpty(userPackage.getUsedmoney()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getUsedmoney());
        mRemainCallMoney.setText(TextUtils.isEmpty(userPackage.getAcctbalance()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getAcctbalance());
        mRemainCallMin.setText(TextUtils.isEmpty(userPackage.getCan_use_sj()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getCan_use_sj());

        mFreeCallAllMin.setText(TextUtils.isEmpty(userPackage.getTotal_sj()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getTotal_sj());
        mFreeCallRemainMin.setText(TextUtils.isEmpty(userPackage.getCan_use_sj()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getCan_use_sj());

        double i2;
        double i1;
        double r;
        if (!TextUtils.isEmpty(userPackage.getTotal_sj()) && !TextUtils.isEmpty(userPackage.getCan_use_sj())) {

            if ("**".equals(userPackage.getTotal_sj()) || "**".equals(userPackage.getCan_use_sj())) {
                mUserFulCllPercent.setSecondaryProgress(0);
            } else {
                i1 = Double.valueOf(userPackage.getTotal_sj());
                i2 = Double.valueOf(userPackage.getCan_use_sj());

                if (i1 == 0 && i2 == 0) {
                    mUserFulCllPercent.setSecondaryProgress(0);
                } else {
                    r = div(i2, i1, 2);
                    r = (1 - r);
                    if (isCacheData) {
                        mUserFulCllPercent.setSecondaryProgress((int) (r * 100));
                    } else {
                        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(mUserFulCllPercent, "secondaryProgress", 0, (int) (r * 100));
                        objectAnimator.setDuration(3000).start();
                    }
                }
            }
        } else {
            mUserFulCllPercent.setSecondaryProgress(0);
        }
        mSMSCounts.setText(TextUtils.isEmpty(userPackage.getTotal_dx()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getTotal_dx());
        mRemainSMSCounts.setText(TextUtils.isEmpty(userPackage.getCan_use_dx()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getCan_use_dx());

        if (!TextUtils.isEmpty(userPackage.getTotal_dx()) && !TextUtils.isEmpty(userPackage.getCan_use_dx())) {
            if ("**".equals(userPackage.getTotal_dx()) || "**".equals(userPackage.getCan_use_dx())) {
                mSMSPercent.setSecondaryProgress(0);
            } else {
                i1 = Double.valueOf(userPackage.getTotal_dx());
                i2 = Double.valueOf(userPackage.getCan_use_dx());
                if (i1 == 0 && i2 == 0) {
                    mSMSPercent.setSecondaryProgress(0);
                } else {
                    r = div(i2, i1, 2);
                    r = (1 - r);
                    if (isCacheData) {
                        mSMSPercent.setSecondaryProgress((int) (r * 100));
                    } else {
                        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(mSMSPercent, "secondaryProgress", 0, (int) (r * 100));
                        objectAnimator.setDuration(3000).start();
                    }
                }
            }
        } else {
            mSMSPercent.setSecondaryProgress(0);
        }
        mTrafficAll.setText(TextUtils.isEmpty(userPackage.getTotal_ll()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getTotal_ll());
        mRemainTraffic.setText(TextUtils.isEmpty(userPackage.getCan_use_ll()) ? getResources().getString(R.string.queryTraffic_default_value) : userPackage.getCan_use_ll());
        if (!TextUtils.isEmpty(userPackage.getTotal_ll()) && !TextUtils.isEmpty(userPackage.getCan_use_ll())) {
            if ("**".equals(userPackage.getTotal_ll()) || "**".equals(userPackage.getCan_use_ll())) {
                mTrafficPercent.setSecondaryProgress(0);
            } else {
                i1 = Double.valueOf(userPackage.getTotal_ll());
                i2 = Double.valueOf(userPackage.getCan_use_ll());
                if (i1 == 0 && i2 == 0) {
                    mTrafficPercent.setSecondaryProgress(0);
                } else {
                    r = div(i2, i1, 2);
                    r = (1 - r);
                    if (isCacheData) {
                        mTrafficPercent.setSecondaryProgress((int) (r * 100));
                    } else {
                        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(mTrafficPercent, "secondaryProgress", 0, (int) (r * 100));
                        objectAnimator.setDuration(3000).start();
                    }
                }
            }
        } else {
            mTrafficPercent.setSecondaryProgress(0);
        }
        isCacheData = false;
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llcx_btn_back:
                onBackPressedSupport();
                break;
            case R.id.user_phone_head_error_layout:
                mHeadErrorLayout.setVisibility(View.GONE);
                mHeadLayout.setVisibility(View.VISIBLE);
                VertifyPhoneNum();
                break;
            default:
                break;
        }
    }

    private String mTelNum = UserLoginInfo.getUserPhone();
    /**
     * 验证手机号类型
     *
     * @param strNum
     */
    private PhoneCardLocation phoneCardInfo;

    private void VertifyPhoneNum() {
        mPresenter.vertifyTelType(mTelNum);
    }

    /**
     * 获取手机号套餐信息
     *
     * @param icp_id   运营商类型
     * @param phoneNum 手机号
     * @param code     验证码  联通用户 code = null
     */
    public void queryPackageInfo(String icp_id, String phoneNum, String code) {
        mLoadLayout.setVisibility(View.VISIBLE);
        mPresenter.getTelSpace(icp_id, phoneNum, code);
    }

    /**
     * 获取验证码
     */
    private void showQueryCodeDialog() {

        if (mVerifyCarDialog != null) {
            mVerifyCarDialog.dismiss();
        }
        mLoadLayout.setVisibility(View.GONE);
        mVerifyCarDialog = new LiuLiangChaXunVerifyCardDialog(LiuLiangChaXunActivity.this, UserLoginInfo.getUserPhone(), phoneCardInfo.getIcp_type());
        mVerifyCarDialog.showDialog();
    }

    /**
     * 两个Double数相除，并保留scale位小数
     *
     * @param v1
     * @param v2
     * @param scale
     * @return Double
     */
    public static Double div(Double v1, Double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.divide(b2, scale, BigDecimal.ROUND_DOWN).doubleValue();
    }

    @Override
    protected void onDestroy() {

        if (llcxSmsObserver != null) {
            getContentResolver().unregisterContentObserver(llcxSmsObserver);
        }
        if (mVerifyCarDialog != null && mVerifyCarDialog.isShowing()) {
            mVerifyCarDialog.cancelDialog();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            chackActivityState();
            if (mLoadLayout.getVisibility() == View.VISIBLE) {
                mLoadLayout.setVisibility(View.GONE);
                return true;
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void queryPremission() {
        LiuLiangChaXunActivityPermissionsDispatcher.onNeedsReadSmsPermissionWithCheck(this);
    }

    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS})
    void onNeedsReadSmsPermission() {
        getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, llcxSmsObserver);
    }

    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS})
    void onPermissionDenied() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LiuLiangChaXunActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private SmsObserver llcxSmsObserver = new SmsObserver(new Handler(), this, new SmsObserver.SmsListener() {
        @Override
        public void onResult(String smsContent) {
            if (activityIsDestory()) {
                return;
            }
            mVerifyCarDialog.setCode(smsContent);
        }
    }, "96400", "");

    @Override
    public void vertifyTelResult(PhoneCardLocation phoneCardLocation) {
        phoneCardInfo = phoneCardLocation;
        if ("0".equals(phoneCardInfo.getStatus())) {
            showDialog(null, getResources().getString(R.string.queryTraffic_query_card_info_error));
            mLoadLayout.setVisibility(View.GONE);
            mHeadErrorLayout.setVisibility(View.VISIBLE);
            mHeadLayout.setVisibility(View.GONE);
            return;
        }
        /**
         * 获取手机号套餐信息
         * 验证手机号类型之后 直接获取手机号的套餐信息  验证码可传null
         */
        mHeadErrorLayout.setVisibility(View.GONE);

        queryPackageInfo(phoneCardInfo.getIcp_type(), mTelNum, null);
    }

    @Override
    public void vertifyTelError() {
        if (activityIsDestory()) {
            return;
        }
        if (mHeadLayout != null && mLoadLayout != null && mHeadErrorLayout != null) {
            mHeadLayout.setVisibility(View.GONE);
            mLoadLayout.setVisibility(View.GONE);
            mHeadErrorLayout.setVisibility(View.VISIBLE);
        }
        showDialog(null, "连接服务器，请检查网络");
    }

    @Override
    public void sendVertifyCode(String result) {

    }

    @Override
    public void sendVertifyCodeError() {

    }

    @Override
    public void getTelSpace(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
            mLoadLayout.setVisibility(View.GONE);
            /**
             * 如果非联通手机号调用此接口
             *      如果后台没有缓存此手机号的套餐信息  则code ！= 200;
             *          并且需要弹出对话框获取验证码  重新请求套餐信息
             *      如果后台缓存了此手机号的套餐信息  则 code = 200;
             */
            JSONObject jsonObject = new JSONObject(result);
            if (!"200".equals(jsonObject.optString("code"))) {
                if ("6011".equals(jsonObject.optString("code"))) {
                    showDialog(null, "查询不到本手机号套餐信息");
                    mLoadLayout.setVisibility(View.GONE);
                    mHeadErrorLayout.setVisibility(View.VISIBLE);
                    mHeadLayout.setVisibility(View.GONE);
                    return;
                } else if ("6012".equals(jsonObject.optString("code"))) {
                    mLoadLayout.setVisibility(View.GONE);
                    mHeadErrorLayout.setVisibility(View.VISIBLE);
                    mHeadLayout.setVisibility(View.GONE);
                    showQueryCodeDialog();
                    return;
                } else {
                    showDialog(null, jsonObject.optString("msg"));
                    mLoadLayout.setVisibility(View.GONE);
                    mHeadErrorLayout.setVisibility(View.VISIBLE);
                    mHeadLayout.setVisibility(View.GONE);
                    return;
                }
            }
            String ll_info = jsonObject.optString("data");
            UserPhoneCardPackageInfoEntity userPackage = JSON.parseObject(ll_info, UserPhoneCardPackageInfoEntity.class);
            App.getApp().getaCache().put(EncryptUtils.encryptMD5ToString(LiuLiangChaXunActivity.class.getName()), ll_info);
            setCacheData(userPackage);
        } catch (JSONException e) {
            e.printStackTrace();
            mLoadLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void getTelSpaceError() {
        if (activityIsDestory()) {
            return;
        }
        String errorMsg;
//        if (!TextUtils.isEmpty(ex.getMessage()) && TIMEOUTERROR.equals(ex.getMessage())) {
//            errorMsg = "连接超时";
//        } else {
        errorMsg = getResources().getString(R.string.connect_service_error);
//        }
        showDialog(null, errorMsg);
        mHeadErrorLayout.setVisibility(View.VISIBLE);
        mHeadLayout.setVisibility(View.GONE);
        mLoadLayout.setVisibility(View.GONE);
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return TelSpaceMainPrecenter.create();
    }


}
